/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate;

import hibernate.exception.BussinessException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @param <T> 
 * @param <ID> 
 * @author ariel
 */
public abstract class GenericDAOHibernate<T, ID extends Serializable> implements GenericDAO<T, ID>{
    
    private Class<T> persistentClass ;
    private SessionFactory session;

    /**
     *
     */
    public GenericDAOHibernate(){
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
    public GenericDAOHibernate(Class<T> T){
        this.persistentClass = T;
    }

    /**
     *
     * @return
     */
    public Session getSession() {
        return session.getCurrentSession();
    }

    public void setSession(SessionFactory session) {
        this.session = session;
    }

    public Class<T> getPersistentClass() {
        return persistentClass;
    }
    
    
    

    /**
     *
     * @return
     * @throws BussinessException
     */
    @Override
    public void create(T entity) throws BussinessException {
       getSession().persist(entity);
    }

    /**
     *
     * @param entity
     * @throws BussinessException
     */
    @Override
    public void saveOrUpdate(T entity) throws BussinessException {
        getSession().saveOrUpdate(entity);
    }

    /**
     *
     * @param id
     * @return
     * @throws BussinessException
     */
    @Override
    public T get(ID id) throws BussinessException {
        T entity =  (T) getSession().get(persistentClass, id);
       if(entity ==null){
            throw new BussinessException();
        }
        return entity;
    }

    /**
     *
     * @param id
     * @throws BussinessException
     */
    @Override
    public void delete(ID id) throws BussinessException {
            this.getSession().delete(get(id));
    }
    
    public void delete(T objeto_borrar) throws BussinessException{
        this.getSession().delete(objeto_borrar);
    }

    /**
     *
     * @return
     * @throws BussinessException
     */
    @Override
    public List<T> findAll() throws BussinessException {
        Session hibernateSession = this.getSession();
        List T = null;
        Query query = hibernateSession.createQuery("from " + this.persistentClass.getName());
        T = query.list();
        return T;
    }   
    
}
